// chain-game.js - 单词接龙游戏逻辑
const { playRightSound, playWrongSound, playClickSound } = require('../../../../utils/audioUtils.js');
const storageManager = require('../../../../manager/storageManager').getInstance();

Page({
  data: {
    score: 0,
    chainLength: 0,
    targetLength: 10,
    combo: 0,
    maxCombo: 0,
    timeLeft: 30,
    currentWord: null,
    lastLetter: '',
    options: [],
    chainWords: [],
    correctAnswers: 0,
    wrongAnswers: 0,
    gameOver: false,
    resultIcon: '',
    resultTitle: '',
    stars: 0,
    accuracy: 0,
    showToast: false,
    toastMessage: '',
    toastIcon: '',
    toastBg: '#4caf50',
    allWords: []
  },

  onLoad: function() {
    // 使用全局实例
    const app = getApp();
    this.wordDataManager = app.globalData.wordDataManager;
    this.magicCoinManager = app.getMagicCoinManager();
    this.timer = null;
    this.initGame();
  },

  onUnload: function() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  },

  // 初始化游戏
  initGame: function() {
    const wordsDict = this.wordDataManager.getAllWords();
    const allWords = Object.values(wordsDict).filter(word => 
      word && word.english && word.chinese && word.english.length >= 3
    );

    if (allWords.length < 10) {
      wx.showToast({
        title: '单词数量不足',
        icon: 'none'
      });
      return;
    }

    // 随机选择起始单词
    const startWord = allWords[Math.floor(Math.random() * allWords.length)];
    const lastLetter = startWord.english.charAt(startWord.english.length - 1).toUpperCase();

    this.setData({
      allWords,
      currentWord: startWord,
      lastLetter,
      chainWords: [{ ...startWord, animation: null }],
      chainLength: 1,
      score: 0,
      combo: 0,
      maxCombo: 0,
      timeLeft: 30,
      correctAnswers: 0,
      wrongAnswers: 0,
      gameOver: false
    });

    this.generateOptions();
    this.startTimer();
  },

  // 生成选项
  generateOptions: function() {
    const { allWords, lastLetter, chainWords } = this.data;
    const usedIds = chainWords.map(w => w.id);

    // 找出以lastLetter开头的单词（正确答案）
    const correctWords = allWords.filter(word => 
      word.english.charAt(0).toUpperCase() === lastLetter && 
      !usedIds.includes(word.id)
    );

    // 找出其他单词（错误答案）
    const wrongWords = allWords.filter(word => 
      word.english.charAt(0).toUpperCase() !== lastLetter && 
      !usedIds.includes(word.id)
    );

    if (correctWords.length === 0) {
      // 没有可用的正确答案，游戏结束
      this.endGame();
      return;
    }

    // 随机选择1个正确答案和2个错误答案
    const correctOption = correctWords[Math.floor(Math.random() * correctWords.length)];
    const shuffledWrong = this.shuffleArray(wrongWords);
    const wrongOptions = shuffledWrong.slice(0, 2);

    // 组合并打乱选项
    const options = this.shuffleArray([
      { ...correctOption, isCorrect: false, isWrong: false, animation: null },
      ...wrongOptions.map(w => ({ ...w, isCorrect: false, isWrong: false, animation: null }))
    ]);

    this.setData({ options });
  },

  // 选择选项
  selectOption: function(e) {
    // 播放点击音效
    playClickSound();
    
    const index = e.currentTarget.dataset.index;
    const selectedWord = this.data.options[index];
    const isCorrect = selectedWord.english.charAt(0).toUpperCase() === this.data.lastLetter;

    if (isCorrect) {
      this.handleCorrectAnswer(selectedWord, index);
    } else {
      this.handleWrongAnswer(index);
    }
  },

  // 处理正确答案
  handleCorrectAnswer: function(word, index) {
    const combo = this.data.combo + 1;
    const maxCombo = Math.max(combo, this.data.maxCombo);
    const baseScore = 100;
    const comboBonus = combo * 10;
    const score = this.data.score + baseScore + comboBonus;
    const chainLength = this.data.chainLength + 1;
    const timeBonus = 3;
    const timeLeft = this.data.timeLeft + timeBonus;

    // 更新选项动画
    const options = this.data.options.map((opt, i) => {
      if (i === index) {
        return { ...opt, isCorrect: true };
      }
      return opt;
    });

    this.setData({
      options,
      score,
      combo,
      maxCombo,
      correctAnswers: this.data.correctAnswers + 1,
      timeLeft
    });

    playRightSound();
    wx.vibrateShort({ type: 'medium' });
    this.showToast('✓', `太棒了！+${baseScore + comboBonus}分`, '#4caf50');

    setTimeout(() => {
      // 添加到链条
      const chainWords = [...this.data.chainWords, { ...word, animation: null }];
      const lastLetter = word.english.charAt(word.english.length - 1).toUpperCase();

      this.setData({
        currentWord: word,
        lastLetter,
        chainWords,
        chainLength
      });

      // 检查是否达到目标
      if (chainLength >= this.data.targetLength) {
        setTimeout(() => this.endGame(), 500);
      } else {
        this.generateOptions();
      }
    }, 800);
  },

  // 处理错误答案
  handleWrongAnswer: function(index) {
    const combo = 0;
    const score = Math.max(0, this.data.score - 50);
    const timePenalty = 5;
    const timeLeft = Math.max(0, this.data.timeLeft - timePenalty);

    // 更新选项动画
    const options = this.data.options.map((opt, i) => {
      if (i === index) {
        return { ...opt, isWrong: true };
      }
      return opt;
    });

    this.setData({
      options,
      score,
      combo,
      wrongAnswers: this.data.wrongAnswers + 1,
      timeLeft
    });

    playWrongSound();
    wx.vibrateShort({ type: 'heavy' });
    this.showToast('✗', '答错了！-50分', '#f44336');

    setTimeout(() => {
      this.generateOptions();
    }, 800);
  },

  // 开始计时
  startTimer: function() {
    this.timer = setInterval(() => {
      const timeLeft = this.data.timeLeft - 1;
      this.setData({ timeLeft });

      if (timeLeft <= 0) {
        this.endGame();
      }
    }, 1000);
  },

  // 打乱数组
  shuffleArray: function(array) {
    const newArray = [...array];
    for (let i = newArray.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
    }
    return newArray;
  },

  // 显示提示信息
  showToast: function(icon, message, bg) {
    this.setData({
      showToast: true,
      toastIcon: icon,
      toastMessage: message,
      toastBg: bg
    });

    setTimeout(() => {
      this.setData({ showToast: false });
    }, 1000);
  },

  // 结束游戏
  endGame: function() {
    if (this.timer) {
      clearInterval(this.timer);
    }

    const totalAttempts = this.data.correctAnswers + this.data.wrongAnswers;
    const accuracy = totalAttempts > 0 ? Math.round((this.data.correctAnswers / totalAttempts) * 100) : 0;
    
    let stars = 0;
    let resultIcon = '';
    let resultTitle = '';

    if (this.data.chainLength >= this.data.targetLength) {
      stars = 3;
      resultIcon = '🏆';
      resultTitle = '完美接龙！';
    } else if (this.data.chainLength >= 7) {
      stars = 2;
      resultIcon = '🌟';
      resultTitle = '表现不错！';
    } else {
      stars = 1;
      resultIcon = '👍';
      resultTitle = '继续加油！';
    }

    // 奖励魔法币
    const coins = stars * 10;
    this.magicCoinManager.addMagicCoins(coins, `单词接龙游戏 - ${stars}星`);

    // 保存游戏记录
    this.saveGameRecord(stars);

    this.setData({
      gameOver: true,
      accuracy,
      stars,
      resultIcon,
      resultTitle
    });
  },

  // 保存游戏记录
  saveGameRecord: function(stars) {
    try {
      const gameStats = storageManager.getStorage(storageManager.STORAGE_KEYS.WORD_GAME_STATS) || {
        totalGamesPlayed: 0,
        totalStars: 0,
        highScore: 0,
        matching: { played: 0, bestScore: 0 },
        scramble: { played: 0, bestScore: 0 },
        memory: { played: 0, bestScore: 0 },
        chain: { played: 0, bestScore: 0 },
        typing: { played: 0, bestScore: 0 },
        puzzle: { played: 0, bestScore: 0 }
      };

      gameStats.totalGamesPlayed += 1;
      gameStats.totalStars += stars;
      gameStats.highScore = Math.max(gameStats.highScore, this.data.score);
      gameStats.chain.played += 1;
      gameStats.chain.bestScore = Math.max(gameStats.chain.bestScore, this.data.score);

      storageManager.setStorage(storageManager.STORAGE_KEYS.WORD_GAME_STATS, gameStats);

      const recentGames = storageManager.getStorage(storageManager.STORAGE_KEYS.RECENT_WORD_GAMES) || [];
      recentGames.unshift({
        id: Date.now(),
        gameName: '单词接龙',
        icon: '🔗',
        score: this.data.score,
        stars,
        timestamp: new Date().toISOString()
      });

      storageManager.setStorage(storageManager.STORAGE_KEYS.RECENT_WORD_GAMES, recentGames.slice(0, 10));
    } catch (error) {
      console.error('保存游戏记录失败:', error);
    }
  },

  // 重新开始游戏
  restartGame: function() {
    // 播放点击音效
    playClickSound();
    this.initGame();
  },

  // 返回
  goBack: function() {
    // 播放点击音效
    playClickSound();
    
    if (this.timer) {
      clearInterval(this.timer);
    }
    wx.navigateBack();
  },
  
  // 转发给朋友
  onShareAppMessage: function() {
    return {
      title: `我在单词接龙游戏中获得了${this.data.score}分！快来挑战吧！`,
      path: '/pages/challenge/word-games/chain-game/chain-game',
      // imageUrl: '/images/challenge.png'
    };
  },
  
  // 分享到朋友圈
  onShareTimeline: function() {
    return {
      title: `我在单词接龙游戏中获得了${this.data.score}分！快来挑战吧！`,
      query: 'from=timeline',
      // imageUrl: '/images/challenge.png'
    };
  }
});
